<template>
    <div id="tree">
        <div class="title">模块信息</div>
        <!-- 制度树 -->
        <el-tree
            ref="tree"
            :data="treeData"
            node-key="id"
            :current-node-key="currentKey"
            default-expand-all
            :default-expanded-keys="expandedKey"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
        >
            <span class="custom-tree-node" slot-scope="{ node }">
                <span :class="{ 'node-level-1': node.level === 1 }">
                    <i v-show="node.level === 1" class="el-icon-folder-opened"></i>
                    {{ node.label }}
                </span>
                <!-- <span class="tree-icon" v-show="activeTab === 'source'">
                    <i v-show="showAddIcon(data)" class="el-icon-folder-add" @click.stop="() => handleTreeNode('add', data)"></i>
                    <i class="yh-edit" v-show="showEditIcon(data)" @click.stop="() => handleTreeNode('edit', data)"></i>
                    <i v-show="showDelIcon(data)" class="el-icon-delete" @click.stop="() => handleTreeNode('del', data)"></i>
                </span> -->
            </span>
        </el-tree>

        <!-- 新增/修改 节点 -->
        <yh-dialog :title="treeNodeTitle" :visible.sync="treeNodeVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
            <div class="main">
                <!-- <span v-for="(itme, index) in delPendingData" :key="index"> {{ itme }} , </span> -->
                <el-form
                    v-if="['add', 'edit'].includes(nodeOperationType)"
                    label-position="top"
                    label-width="80px"
                    @submit.native.prevent
                    :model="submitForm"
                >
                    <el-form-item label="制度类型:" required>
                        <el-input v-model="submitForm.name" placeholder="请输入" size="mini"></el-input>
                    </el-form-item>
                </el-form>
                <p v-else>是否删除 {{ nodeOperationData.label }} ?</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="reset">取消</el-button>
                <el-button size="mini" type="primary" @click="submit">确定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import API from '../api/report-manage';

@Component({ name: 'Tree', components: {} })
export default class Tree extends Vue {
    @Prop() activeTab: string;

    treeData: any[] = []; // 树数据
    expandedKey: string[] = ['0'];
    currentKey: string = '1';
    currentNode: any = null;

    treeNodeVisible: boolean = false;
    nodeOperationType: string = ''; // add|edit|del
    nodeOperationData: any = {};

    submitForm: any = { name: '' };

    async mounted() {
        this.getTreeData();
    }

    get treeNodeTitle() {
        const enums = { add: '新增', edit: '修改', del: '删除' };
        return `${enums[this.nodeOperationType]}类型`;
    }

    getTreeData() {
        this.treeData = [{ id: '0', label: '事后监督系统', level: 1, children: [{ id: '1', label: '私募基金', level: 2 }] }];
    }

    /**
     * 树节点操作事件
     * @operation 操作类型 add|edit|del
     * @node 树节点
     */
    handleTreeNode(operation, node): void {
        this.nodeOperationType = operation;
        this.nodeOperationData = node;
        if (operation === 'edit') {
            this.submitForm.name = node.label;
        }
        this.treeNodeVisible = true;
    }

    submit(): void {
        if (!this.verify()) return;

        // if (this.nodeOperationType === 'add') {
        //     const data = {
        //         parentId: this.nodeOperationData.id,
        //         label: this.submitForm.name,
        //         articleType: this.nodeOperationData.articleType,
        //         level: this.nodeOperationData.level + 1,
        //     };
        //     API.addTreeNode(data).then((res: any) => {
        //         this.reset();
        //         this.getTreeData();
        //         this.yh_message_success('新增成功!');
        //     });
        // } else if (this.nodeOperationType === 'edit') {
        //     const data = {
        //         id: this.nodeOperationData.id,
        //         label: this.submitForm.name,
        //         articleType: this.nodeOperationData.articleType,
        //     };
        //     API.updateTreeNode(data).then((res: any) => {
        //         this.reset();
        //         this.getTreeData();
        //         this.yh_message_success('修改成功!');
        //     });
        // } else if (this.nodeOperationType === 'del') {
        //     const data = {
        //         id: this.nodeOperationData.id,
        //         articleType: this.nodeOperationData.articleType,
        //     };
        //     API.deleteTreeNode(data).then((res: any) => {
        //         this.reset();
        //         this.getTreeData();
        //         this.yh_message_success('删除成功!');
        //     });
        // }
    }

    reset(): void {
        this.treeNodeVisible = false;
        setTimeout(() => {
            this.nodeOperationType = '';
            this.nodeOperationData = {};
            this.submitForm.name = '';
        }, 500);
    }

    verify() {
        if (!this.submitForm.name.trim() && ['add', 'edit'].includes(this.nodeOperationType)) {
            this.yh_message_warn('请填写合同类型名称!');
            return false;
        }
        return true;
    }

    handleNodeClick(data, node): void {
        console.log('树节点切换:', data);
        this.currentNode = data;
        this.$emit('handleTreeNodeData', data);
    }

    /**
     * 是否展示该节点的新增ICON
     * @node 树节点
     */
    showAddIcon(node): boolean {
        // 1. 制度树5层后不允许新增, 合同树4层
        if (node.sourceCode) {
            return false;
        }

        if (node.isProduct) {
            return false;
        }
        return true;
    }

    showEditIcon(node): boolean {
        if (node.isProduct) {
            return false;
        }
        return true;
    }

    /**
     * 是否展示该节点的删除ICON
     * @node 树节点
     */
    showDelIcon(node): boolean {
        // 1. 第一层的监管类和内规类 不允许删除
        if (Number(node.level === 1)) {
            return false;
        }
        // 2. 具体的产品 不允许删除
        if (node.isProduct) {
            return false;
        }
        return true;
    }

    /**
     * 在树结构中查找某个节点， 并返回与之关联的节点
     */
    findNode(tree, targetId, result = []) {
        for (let i = 0; i < tree.length; i++) {
            const { id, children } = tree[i];
            if (id === targetId) {
                return result.concat(tree[i]);
            } else if (children) {
                const res = this.findNode(children, targetId, result.concat(tree[i]));
                if (res) {
                    return res;
                }
            }
        }
        return null;
    }

    /**
     * 对象数组 根据对象内的某个属性去重
     */
    uniqueById(arr) {
        const map = {};
        const result = [];
        for (let i = 0; i < arr.length; i++) {
            const item = arr[i];
            if (!map[item.id]) {
                map[item.id] = true;
                delete item.children;
                result.push(item);
            }
        }
        return result;
    }
}
</script>
<style lang="scss" scoped>
#tree {
    height: 100%;

    .title {
        padding-left: 10px;
        border: 1px solid #efefef;
        border-right: none;
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        font-weight: bold;
        color: #575757;
    }

    .el-button-group {
        width: 100%;
        display: flex;
        padding: 10px;

        .el-button {
            flex: 1;
            background: #f9f9f9;
            padding: 0;

            /deep/ span {
                width: 90%;
                height: 24px;
                margin: 4px 0;
                line-height: 24px;
            }
        }

        .active {
            color: var(--primary);

            /deep/ span {
                background: #fff;
                font-weight: 700;
            }
        }
    }

    /deep/ .el-tree {
        padding: 10px;
        height: calc(100% - 40px);
        overflow: auto;

        .el-tree-node__content:hover {
            background: #f9f9f9;
            border-radius: 5px;

            i {
                display: inline-block;
            }
        }

        .tree-icon {
            position: absolute;
            right: 10px;

            i {
                font-size: 12px;
                padding: 0 5px;
                display: none;
            }
        }

        .node-level-1 {
            font-weight: bold;
            i {
                font-weight: bold;
            }
        }
    }
}

/deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: #fef7eb;
    border-radius: 5px;

    .custom-tree-node {
        color: var(--primary);
        font-weight: bold;
    }
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    content: '*' !important;
    margin-right: 2px !important;
    color: red;
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:after {
    display: none;
}

/deep/ .el-dialog {
    .el-dialog__header {
        background: #f9f9f9;

        .el-dialog__title,
        .el-dialog__headerbtn .el-dialog__close {
            color: #333333;
        }
    }

    .el-dialog__body .el-form-item__label {
        height: 30px;
        /* vertical-align: bottom; */
        overflow: visible;
        padding: 0;
        font-size: 12px;
    }

    .el-dialog__footer {
        text-align: right;
        border-top: none;
        .el-button {
            min-width: 50px;
            border-radius: 4px;
        }
        .el-button + .el-button {
            margin-left: 10px;
        }

        .dialog-footer {
            padding: 0 10px;
        }
    }
}

/deep/ .el-tree-node__content:hover {
    .custom-tree-node {
        height: 21px;
        line-height: 21px;
        span:first-child {
            display: inline-block;
            width: 150px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
}
</style>
